(function(){

    var ShortURL = require('./ShortURL.js');
    var config = require('./config.js');

    var tools = {
        isURL: function(url){
            if(!url || typeof url !== "string" || url.length === 0)return false;
            return /^(http|https|ftp|ftps|git|svn|news|nntpurl|telnet|Gopher|Wais|Mailto|File|sms|Prosperurl).*?:\/\/.*?([a-zA-Z0-9_-]|\/)+$/i.test(url);
        },
        dataFormat: function(data, format){
            var content = '';
            switch (format){
                case 'xml':
                    content = '<?xml version="1.0" encoding="utf-8"?>\
                        <root>\
                        <error>'+data.error+'</error>\
                        <url>'+data.url+'</url>\
                </root>\
                ';
                    break;
                case 'json':
                    content = JSON.stringify(data);
                    break;
                case 'js':
                    content = 'var short_url={error:'+data.error+',url:"'+data.url+'"};';
                    break;
                case 'text':
                    content = data.url || data.error;
                    break;
                case 'jsonp':
                    content = 'www_50r_cn_jsonp_callback('+JSON.stringify(data)+')';
                    break;
                default :
                    content = JSON.stringify(data);
            }
            return content;
        },
        sendFormat: function(data, format){
            var mime = {
                'json':     'application/json',
                'jsonp':    'text/javascript',
                'js':       'text/javascript',
                'text':     'text/plain',
                'xml':      'text/xml'
            };
            this.set('Content-Type',mime[format]||mime['json']);
            this.send(tools.dataFormat(data,format));
        },
        addURL: function(req, res){
            var dataType = req.query.dataType || 'json';
            var url = req.query.url;
            if(tools.isURL(url)){
                var shortURL = new ShortURL(req, res);
                shortURL.getUrlKey(url, function(key, exists){
                    if(!exists){
                        shortURL.add({
                            url: url
                        }, function(err,key){
                            if(key){
                                tools.sendFormat.call(res, {error: null, url: config.domain + '/' + key},dataType);
                            }else{
                                tools.sendFormat.call(res, {error:err.message, url:null},dataType);
                            }
                            shortURL.db.close();
                        });
                    }else{
                        shortURL.db.close();
                        tools.sendFormat.call(res, {error: null, url:config.domain + '/' + key}, dataType);
                    }
                });
            }else{
                tools.sendFormat.call(res, {error:'错误的URL!', url:null}, dataType);
            }
        },
        get:function(req, res){
            var code = req.params.code;
            if(/^[a-zA-Z0-9_]{6}$/.test(code)){
                var s = new ShortURL(req, res);
                s.getURL(code, function(data){
                    var url = '';
                    if(data && 'url' in data)url = data.url;
                    if(tools.isURL(url)){
                        res.redirect(url)
                    }else{
                        res.redirect('/');
                    }
                    s.db.close();
                });
            }else{
                res.redirect('/');
            }
        }
    };

    module.exports = tools;
})();